<?php


namespace app\app\controller;


use EasyWeChat\Factory;
use think\Db;

class WxUser extends UserBase
{
    /**
     * 获取用户信息
     */
    public function GetWxUserInfo()
    {
        msg(0, '查询成功', $this->memberInfo);
    }

    /**
     * 通过默认地址获取最近的服务站
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWaterStation()
    {
        $where[] = ['status', '=', 1];
        $where[] = ['operation_status', '=', 1];
        $AddressData = $this->getAddress();
        if (!$AddressData) {
            responseJson(-1, '无默认地址,请先添加', '');
        }
        $where[] = ['city', '=', $AddressData['city']];
        $business = Db::name('business')
            ->field('id,member_id,province,city,area,business_name,address,phone,longitude,latitude')
            ->where($where)
            ->select();
        if (!$business) {
            responseJson(-1, '当前地区无配送服务站请拨打电话', '');
        }
        //todo 通过当前定位获取服务站列表改为通过默认地址获取最近服务站
//        $from = $data['latitude'] . ',' . $data['longitude'];

        $from = $AddressData['latitude'] . ',' . $AddressData['longitude'];
        foreach ($business as $k => $v) {
//            $to = $from . ';' . $v['latitude'] . ',' . $v['longitude'];
//            $business[$k]['distance'] = getDistance($from, $to);
            $business[$k]['distance'] = distanceHaversine($AddressData['latitude'], $AddressData['longitude'], $v['latitude'], $v['longitude']);
            $business[$k]['distance'] = floor($business[$k]['distance'] * 1000);
        }
        $business_short = array_reduce($business, function ($carry, $item) {
            return ($item['distance'] < $carry['distance']) ? $item : $carry;
        }, $business[0]);
        responseJson(0, '查询成功', $business_short);
    }

    //获取服务站列表 and 搜索 and 选择地址
    public function getWaterList()
    {
        $data = $this->request->param();
        isset($data['address_id']) ? $AddressData = $this->getAddressById($data['address_id']) : $AddressData = $this->getAddress();
        if (!$AddressData) {
            msg(-1, '地址不存在，请添加地址', $AddressData);
        }
        $from = $AddressData['latitude'] . ',' . $AddressData['longitude'];
        if ($data['address']) {
            $where[] = ['address', 'like', '%' . $data['address'] . '%'];
        }
        $where[] = ['status', '=', 1];
        $where[] = ['operation_status', '=', 1];
        $business = Db::name('business')
            ->field('id,member_id,province,city,area,business_name,address,phone,longitude,latitude')
            ->where($where)
            ->select();
        $area_distance = config('site.water_station_distance') ? config('site.water_station_distance') : 5000;
        $can_business_distance = config('site.can_water_station_distance') ? config('site.can_water_station_distance') : 6000;
        foreach ($business as $k => $v) {
            $to = $from . ';' . $v['latitude'] . ',' . $v['longitude'];
//            $business[$k]['distance'] = getDistance($from, $to);
            $business[$k]['distance'] = distanceHaversine($AddressData['latitude'], $AddressData['longitude'], $v['latitude'], $v['longitude']);
            $business[$k]['distance'] = floor($business[$k]['distance'] * 1000);
            $business[$k]['map_icon'] = config('site.wx_map_icon');
            if ($business[$k]['distance'] > $can_business_distance) {
                unset($business[$k]);
                continue;
            }
            if ($business[$k]['distance'] > $area_distance) {
                $business[$k]['is_delivery'] = false;
            } else {
                $business[$k]['is_delivery'] = true;
            }

        }
        usort($business, function ($a, $b) {
            return $a['distance'] - $b['distance'];
        });
        msg(0, "查询成功", $business);
    }


    /**
     * 获取默认地址
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getDefaultAddress()
    {
        $data = $this->getAddress();
        msg(0, '查询成功', $data);
    }

    /**
     * 通过id获取地址
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getAddress2()
    {
        $data = $this->request->param();
        $addressData = $this->getAddressById($data['id']);
        msg(0, '查询成功', $addressData);
    }

    //获取地址列表
    public function getAddressList()
    {
        $member_id = $this->memberInfo['id'];
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $member_id];
        $data = Db::name('delivery_address')
            ->where($where)
            ->order('is_default_address desc')
            ->order('create_time desc')
            ->select();
        msg(0, "查询成功", $data);
    }

    //增加收货地址
    public function addAddress()
    {
        $data = $this->request->param();
        $save_data = array(
            'member_id' => $this->memberInfo['id'],
            'realname' => $data['realname'],
            'telphone' => $data['telphone'],
            'province' => $data['province'],
//            'latitude' => $data['latitude'],
//            'longitude' => $data['longitude'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'is_default_address' => $data['is_default_address'],
            'create_time' => time()
        );
        $address = getLWByAddress($save_data['province'] . $save_data['city'] . $save_data['area'] . $save_data['address']);
        $address = json_decode($address, true);
        if ($address['code'] == 0) {
            $save_data['longitude'] = $address['data'][0];
            $save_data['latitude'] = $address['data'][1];
        } else {
            msg(-1, '输入正确位置', '');
        }
        Db::startTrans();
        try {
            if ($data['is_default_address']) {
                Db::name('delivery_address')
                    ->where(['member_id' => $this->memberInfo['id']])
                    ->update(['is_default_address' => 0]);
            }
            $insert_id = Db::name('delivery_address')->insertGetId($save_data);
            Db::commit();
            msg(0, '添加成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //编辑收货地址
    public function editAddress()
    {
        $data = $this->request->param();
        $save_data = array(
            'realname' => $data['realname'],
            'telphone' => $data['telphone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'is_default_address' => $data['is_default_address'],
        );
        $address = getLWByAddress($save_data['province'] . $save_data['city'] . $save_data['area'] . $save_data['address']);
        $address = json_decode($address, true);
        if ($address['code'] == 0) {
            $save_data['longitude'] = $address['data'][0];
            $save_data['latitude'] = $address['data'][1];
        } else {
            msg(-1, '输入正确位置', '');
        }
        Db::startTrans();
        try {
            if ($data['is_default_address']) {
                Db::name('delivery_address')
                    ->where(['member_id' => $this->memberInfo['id']])
                    ->update(['is_default_address' => 0]);
            }
            $num = Db::name('delivery_address')
                ->where(['id' => $data['id']])
                ->update($save_data);
            Db::commit();
            msg(0, '编辑成功', $num);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }
    //删除收货地址

    /**
     * 添加发票信息
     */
    public function addInvoice()
    {
        $data = $this->request->param();
        $insertData = array(
            'invoice_type' => $data['invoice_type'],
            'invoice_head' => $data['invoice_head'],
            'tax_no' => $data['tax_no'],
            'email' => $data['email'],
            'bank' => $data['bank'],
            'bank_address' => $data['bank_address'],
            'bank_phone' => $data['bank_phone'],
            'bank_no' => $data['bank_no'],
            'company_address' => $data['company_address'],
            'invoice_remark' => $data['invoice_remark'],
            'member_id' => $this->memberId
        );
        Db::startTrans();
        try {

            $id = Db::name('invoice_msg')->insertGetId($insertData);
            Db::commit();
            msg(0, '查询成功', $id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 编辑发票信息
     */
    public function editInvoice()
    {
        $data = $this->request->param();
        $insertData = array(
            'invoice_type' => $data['invoice_type'],
            'invoice_head' => $data['invoice_head'],
            'tax_no' => $data['tax_no'],
            'email' => $data['email'],
            'bank' => $data['bank'],
            'bank_address' => $data['bank_address'],
            'bank_phone' => $data['bank_phone'],
            'bank_no' => $data['bank_no'],
            'company_address' => $data['company_address'],
            'invoice_remark' => $data['invoice_remark'],
        );
        Db::startTrans();
        try {
            $id = Db::name('invoice_msg')
                ->where('member_id', $this->memberId)
                ->update($insertData);
            Db::commit();
            msg(0, '查询成功', $id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     *发票信息
     */
    public function getInvoice()
    {
        $data = Db::name('invoice_msg')
            ->where('member_id', $this->memberId)
            ->find();
        msg(0, '查询成功', $data);
    }

    /**
     * 下订单
     */
    public function createOrder()
    {
        $data = $this->request->param();
        $goods_id = $data['goods_id'];
        $num = $data['num'];
        $goods_mgs = $this->getGoodsById($goods_id);
        $price = $goods_mgs['price'] * $num;
        if (!$goods_mgs) {
            msg(-1, '商品不存在', '');
        }
        $order_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
//            'business_id' => $data['business_id'],
            'price' => $price,
            'status' => 0, //'0待支付 1待发货 2待收货 3已完成 4已取消 5售后',
            'pay_status' => 0,
            'address_id' => $data['address_id'],
            'create_time' => time(),
            'remark' => $data['remark'],
        );
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            //todo 返回订单信息
            $order_id = Db::name('order')->insertGetId($order_data);
            $order_detail_data = [
                'order_id' => $order_id,
                'goods_id' => $goods_id,
                'goods_cate' => $goods_mgs['cate_id'],
                'goods_name' => $goods_mgs['name'],
                'goods_price' => $goods_mgs['price'],
                'write_price' => $goods_mgs['write_price'] * $num,
                'purchase_price' => $goods_mgs['purchase_price'] * $num,
                'goods_num' => $num,
                'subtotal' => $goods_mgs['price'] * $num
            ];
            $order_data['id'] = (int)$order_id;
            Db::name('order_detail')->insertGetId($order_detail_data);
            //获取收货地址
            $order_data['delivery_address'] = Db::name('delivery_address')->find($data['address_id']);
            //获取商品信息
            $order_data['order_detail'] = Db::name('order_detail')
                ->where('order_id', '=', $order_id)
                ->find();
            $order_data['goods_detail'] = Db::name('goods')
                ->find($order_data['order_detail']['goods_id']);
            Db::commit();
            $order_data['create_time'] = date('Y-m-d H:i', $order_data['create_time']);
            msg(0, '查询成功', $order_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 获取个人订单列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderList()
    {
        //0 全部 1待支付         3待收货 4已完成
        //      '0待支付 1待发货 2待收货 3已完成 4已取消 5售后',
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['is_del', '=', 0];
        $where[] = ['business_id', '<>', ''];
        if (isset($data['status'])) {
            $where[] = ['status', '=', $data['status']];
        }
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $data = Db::name('order')
            ->order('create_time desc')
            ->where($where)
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) use ($app) {
                $item['order_detail'] = Db::name('order_detail')->where('order_id', '=', $item['id'])->find();
                $item['goods_detail'] = Db::name('goods')->find($item['order_detail']['goods_id']);
                $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                $item['address'] = Db::name('delivery_address')->where('id',$item['address_id'])->find();
                if ($item['status'] == 0) {
                    $res = $app->order->queryByOutTradeNumber($item['order_no']);
                    if ($res['trade_state'] == "SUCCESS") {
                        $this->orderPaySuccess($item['id'], 2);
                    }
                }
                return $item;
            });
        msg(0, '查询完成', $data);
    }

    /**
     * 获取订单详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrderDetail()
    {
        $id = input('id/d', 1);
        try {
            $order = Db::name('order')
                ->field('id,order_no,price,status,pay_type,create_time,remark,pay_status,write_code,write_status,business_id,address_id,write_code_digits')
                ->find($id);
            //生成订单核销四位数核销码
            if ($order['pay_status'] == 1 && (!$order['write_code_digits'])) {
                $write_code_digits = rand(1000, 9999);
                $update_order = array(
                    'id' => $id,
                    'write_code_digits' => $write_code_digits
                );
                Db::name('order')->update($update_order);
                $order['write_code_digits'] = $write_code_digits;
            }
            $order['create_time'] = date('Y-m-d H:i', $order['create_time']);
            $order['order_detail'] = Db::name('order_detail')
                ->where('order_id', '=', $order['id'])
                ->find();
            $order['goods_detail'] = Db::name('goods')
                ->find($order['order_detail']['goods_id']);
            //服务站信息
            $order['business'] = Db::name('business')
                ->where('id', $order['business_id'])
                ->find();
            //收货地址信息
            $order['delivery_address'] = Db::name('delivery_address')
                ->where('id', $order['address_id'])
                ->find();
            //当前产品可用水票
            $order['ticket_num'] = 0;
            $ticket = Db::name('ticket_category')
                ->where('goods_id', $order['goods_detail']['id'])
                ->find();
            if ($ticket) {//存在说明为水票产品
                $where[] = ['member_id', '=', $this->memberId];
                $where[] = ['goods_id', '=', $order['goods_detail']['id']];
                $member_ticket = Db::name('member_ticket')
                    ->where($where)
                    ->find();
                if ($member_ticket) {
                    $order['ticket_num'] = $member_ticket['num'];
                }
            }
            Db::commit();
            msg(0, '', $order);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 获取我的水票
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMyTicket()
    {
        $data = Db::name('member_ticket')
            ->where('member_id', $this->memberId)
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['ticket_category'] = Db::name('ticket_category')->find($v['ticket_cate']);
        }
        msg(0, '查询完成', $data);
    }

    /**
     * 设置订单状态
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setOrderStatus()
    {
        $data = $this->request->param();
        $update = array(
            'status' => $data['status'],
            'id' => $data['id']
        );
        //'0待支付 1待发货 2待收货 3已完成 4已取消 5售后',
        $order = Db::name('order')->update($update);
        msg(0, '查询完成', $order);
    }

    //删除订单
    public function delOrder()
    {
        $data = $this->request->param();
        $update = array(
            'is_del' => 1,
            'id' => $data['id']
        );
        $order = Db::name('order')->update($update);
        if ($order) {
            msg(0, '查询完成', $order);
        }
        msg(-1, '删除失败', '');
    }


    //申请退款
    public function applyRefund()
    {
        //已经支付 1未到货 2收到货
        $data = $this->request->param();
        $insert_data = array(
            'order_id' => $data['order_id'],
            'business_id' => $data['business_id'],
            'member_remark' => $data['member_remark'],
            'member_id' => $this->memberId,
            'status' => 1,
            'create_time' => time(),
        );
        Db::startTrans();
        try {
            $order_after_id = Db::name('order_after')->insertGetId($insert_data);
            $order_update = array(
                'status' => 5,
                'id' => $data['order_id']
            );
            Db::name('order')->update($order_update);
            Db::commit();
            msg(0, '增加成功', $order_after_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    /**
     * 申请商户
     */
    public function addBusiness()
    {
        $data = $this->request->param();
        $result = $this->validate($data, 'Business.insert');
        if (true !== $result) {
            msg(-1, $result, '');
        }
        $create_time = time();
        $data = array(
            'member_id' => $this->memberId,
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'business_name' => $data['business_name'],
            'address' => $data['address'],
            'name' => $data['name'],
            'phone' => $data['phone'],
            'username' => $data['username'],
            'password' => md5($data['password'] . 'business'),
            'solt' => md5($create_time . $data['password']),
            'id_font' => $data['id_font'],
            'id_back' => $data['id_back'],
            'business_license' => $data['business_license'],
            'other_license' => $data['other_license'],
            'amount' => 0.00,//账户余额
            'status' => 0,
            'create_time' => $create_time,
            'operation_status' => 0,

            'yingye_name' => $data['yingye_name'],
            'bank_name' => $data['bank_name'],
            'bank_no' => $data['bank_no'],
            'yingye_address' => $data['yingye_address'],
            'receive_email' => $data['receive_email'],
        );
        $address = getLWByAddress($data['province'] . $data['city'] . $data['area'] . $data['address']);
        $address = json_decode($address, true);
        if ($address['code'] == 0) {
            $data['longitude'] = $address['data'][0];
            $data['latitude'] = $address['data'][1];
        } else {
            msg(-1, '输入正确位置', '');
        }
        Db::startTrans();
        try {
            $where1[] = ['member_id', '=', $this->memberId];
            $business = Db::name('business')->where($where1)->find();
            if ($business) {
                msg(-1, '账号已申请', []);
            }
            $where[] = ['member_id', '<>', $this->memberId];
            $where[] = ['username', '=', $data['username']];
            $business = Db::name('business')->where($where)->find();
            if ($business) {
                msg(-1, '账号已存在,请输入其他账号', []);
            }
            $business_id = Db::name('business')->insertGetId($data);
            Db::commit();
            msg(0, '查询成功', $business_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    public function memberToBusiness()
    {
        $data = Db::name('business')->where(['member_id' => $this->memberId])->find();
        if ($data) {
            if ($data['status'] == 1) {
                msg(0, '申请已通过', '');
            }
            msg(1, '你已申请，等待审核', '');
        }
        msg(-1, '未申请', '');
    }

    //使用水票支付订单
    public function payOrderByTicket()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $order = Db::name('order')->find($order_id);
        $order_detail = Db::name('order_detail')
            ->where(['order_id' => $order_id])
            ->find();
        if (!$order) {
            msg(-1, '订单不存在', '');
        }
        if ($order['status'] != 0) {
            msg(-1, '订单状态已支付', '');
        }
        $shopGoods = Db::name('ticket_category')
            ->where('goods_id', '=', $order_detail['goods_id'])
            ->find();
        if (!$shopGoods) {
            msg(-1, '商品未开通水票购买', '');
        }
        Db::startTrans();
        try {
            //增加服务站id business_id address_id
            $order_update_data = array(
                'id' => $data['order_id'],
                'business_id' => $data['business_id'],
                'address_id' => $data['address_id'],
            );
            Db::name('order')->update($order_update_data);

            $where[] = ['member_id', '=', $this->memberId];
            $where[] = ['goods_id', '=', $order_detail['goods_id']];
            $my_ticket = Db::name('member_ticket')
                ->where($where)->find();
            if ($order_detail['goods_num'] > $my_ticket['num']) {
                msg(-1, '水票数量不足，请购买', '');
            }
            $member_ticket = Db::name('member_ticket')
                ->where($where)
                ->setDec('num', $order_detail['goods_num']);
            //更改订单状态
            $this->orderPaySuccess($order_id, 1);
            //水票使用历史
            $this->waterTicketHistory($my_ticket['ticket_cate'], $my_ticket['goods_id'], $order_detail['goods_num'], 2);
            Db::commit();
            msg(0, '支付完成', $member_ticket);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //用户购买商品直接支付
    public function wapayUserGoods()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_type = $data['order_type']; //1服务站订单 2用户订单 3用户水票订单 目前走通服务站订单
        $orderdata = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->where('pay_status', '=', 0)
            ->find();
        if (!$orderdata) {
            msg(-1, '订单有误', '');
        }
        //增加服务站id business_id address_id
        $order_update_data = array(
            'id' => $orderdata['id'],
            'business_id' => $data['business_id'],
            'address_id' => $data['address_id'],
        );
        Db::name('order')->update($order_update_data);
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $userinfo = $this->memberInfo;
        $jssdk = $app->jssdk;
        $result = $app->order->unify([
            'body' => '用户购水',
            'out_trade_no' => $orderdata['order_no'],
            'total_fee' => $orderdata['price'] * 100,
            //todo 测试一分钱
            //           'total_fee' => 1,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userinfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $orderdata['order_no'];
            $result['order_id'] = $orderdata['id'];
            $result['type'] = $order_type;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }
    //购买商品支付回调
    //支付完成后回调
    public function uporderUserGoods()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_type = $data['order_type'];
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        $res = $app->order->queryByOutTradeNumber($order_no);
        if ($res['trade_state'] == "SUCCESS") {
            //服务站支付成功后自己写逻辑 并返回
            $this->orderPaySuccess($order_data['id'], 2);
            $order_data = Db::name('business_order')
                ->where('order_no', '=', $order_no)
                ->find();
            msg(0, "支付成功！", $order_data);
        } else {
            msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
        }
    }

    //水票订单创建
    public function waterOrder()
    {
        $data = $this->request->param();
        $water_ticket_id = $data['water_ticket_id'];//水票购买套餐id
        $water_ticket_info = Db::name('water_ticket')->find($water_ticket_id);
        if (!$water_ticket_info) {
            msg(-1, '购买套餐不存在', '');
        }
        $insert_data = array(
            'order_no' => GetOrderSN(2) . $this->memberId,
            'member_id' => $this->memberId,
            'water_ticket_id' => $water_ticket_id,
            'create_time' => time(),
            'status' => 0,
            'price' => $water_ticket_info['price']
        );
        Db::startTrans();
        try {
            $member_watero_id = Db::name('member_watero')->insertGetId($insert_data);
            $insert_data['id'] = $member_watero_id;
            Db::commit();
            msg(0, '新增成功', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //水票订单发起支付
    public function wapayWaterOrder()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_type = $data['order_type']; //1服务站订单 2用户订单 3用户水票订单 目前走通服务站订单
        $orderdata = Db::name('member_watero')
            ->where('order_no', '=', $order_no)
            ->where('status', '=', 0)
            ->find();
        if (!$orderdata) {
            msg(-1, '订单有误', '');
        }
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $userinfo = $this->memberInfo;
        $jssdk = $app->jssdk;
        $result = $app->order->unify([
            'body' => '用户购水',
            'out_trade_no' => $orderdata['order_no'],
            'total_fee' => $orderdata['price'] * 100,
            //todo 测试一分钱
            //           'total_fee' => 1,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userinfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $orderdata['order_no'];
            $result['order_id'] = $orderdata['id'];
            $result['type'] = $order_type;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //购买水票完成后回调
    public function uporderWaterOrder()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_type = $data['order_type'];
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $order_data = Db::name('member_watero')
            ->where('order_no', '=', $order_no)
            ->find();
        $res = $app->order->queryByOutTradeNumber($order_no);
        if ($res['trade_state'] == "SUCCESS") {
            //修改订单状态
            $update_data = array(
                'id' => $order_data['id'],
                'pay_time' => time(),
                'status' => 1
            );
            Db::name('member_watero')->update($update_data);
            //水票套餐信息 tcategory_id水票类型id price价格 count数量 rebate
            $water_ticket_data = Db::name('water_ticket')->find($order_data['water_ticket_id']);
            //水票信息 num单桶、单瓶规格 goods_cate商品分类 goods_id可核销商品id
            $ticket_category = Db::name('ticket_category')->find($water_ticket_data['tcategory_id']);
            //增加水票
            $where1[] = ['member_id', '=', $this->memberId];
            $where1[] = ['goods_id', '=', $ticket_category['goods_id']];
            $insert_ticket = Db::name('member_ticket')->where($where1)->find();
            if ($insert_ticket) {
                Db::name('member_ticket')
                    ->where($where1)
                    ->setInc('num', $water_ticket_data['count']);
            } else {
                Db::name('member_ticket')->insertGetId(
                    array(
                        'ticket_cate' => $water_ticket_data['tcategory_id'],
                        'member_id' => $this->memberId,
                        'num' => $water_ticket_data['count'],
                        'goods_id' => $ticket_category['goods_id']
                    )
                );
            }
            //插入水票历史
            //$ticket_cate, $goods_id, $num, $type
            $this->waterTicketHistory($water_ticket_data['tcategory_id'], $ticket_category['goods_id'], $water_ticket_data['count'], 1);
            //服务站返利 更新服务站余额
            if ($this->memberInfo['belong_business_id']) {
                Db::name('business')
                    ->where('id', $this->memberInfo['belong_business_id'])
                    ->setInc('amount', $water_ticket_data['rebate']);
                Db::name('business_finance')->insertGetId(
                    array(
                        'business_id' => $this->memberInfo['belong_business_id'],
                        'amount' => $water_ticket_data['rebate'],
                        // 'status' => 1,
                        'type' => 1,
                        'create_time' => time(),
                        'is_count' => 1,
                        'desc' => '推广返利'
                    )
                );
            }
            msg(0, "支付成功！", $order_data);
        } else {
            msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
        }
    }

    //删除地址
    public function delAddress()
    {
        $data = $this->request->param();
        $update = array(
            'id' => $data['address_id'],
            'is_del' => 1
        );
        $order_data = Db::name('delivery_address')->update($update);
        msg(0, "删除成功", $order_data);
    }

    //用户购买水票返利 todo 整合


    //订单支付完成状态更改
    public function orderPaySuccess($order_id, $pay_type)
    {//'支付方式 1水卡支付 2直接支付'
        //生成订单二维码 todo 增加页面路径
        $qr_code = qrcode('order_id', $order_id, 'pages/myOrder/orderDeta/orderDeta', 400);
        //返回插入
        $update_data = array(
            'id' => $order_id,
            'status' => 1,//0待支付 1待发货 2待收货 配送中 3已完成 4已取消 5售后'
            'pay_type' => $pay_type,//'支付方式 1水卡支付 2直接支付'
            'pay_time' => time(),
            'pay_status' => 1,
            'write_code' => $qr_code
        );
        //增加商品销量
        $goods_detail = Db::name('order_detail')->where('order_id', $order_id)->find();
        Db::name('goods')
            ->where('id', $goods_detail['goods_id'])
            ->setInc('count', $goods_detail['goods_num']);
        return Db::name('order')->update($update_data);
    }

    //水票使用历史插入公用
    public function waterTicketHistory($ticket_cate, $goods_id, $num, $type)
    {
        $insert_data = array(
            'member_id' => $this->memberId,
            'ticket_cate' => $ticket_cate,
            'goods_id' => $goods_id,
            'num' => $num,
            'type' => $type,//'1 加 2减',
            'create_time' => time(),
        );
        $data_id = Db::name('member_ticket_history')->insertGetId($insert_data);
        return $data_id;
    }

    public function getTicketByGoodsId()
    {
        $data = $this->request->param();
        $goods_id = $data['goods_id'];
        $ticket_num = 0;
        $ticket = Db::name('ticket_category')
            ->where('goods_id', $goods_id)
            ->find();
        if ($ticket) {//存在说明为水票产品
            $where[] = ['member_id', '=', $this->memberId];
            $where[] = ['goods_id', '=', $goods_id];
            $member_ticket = Db::name('member_ticket')
                ->where($where)
                ->find();
            if ($member_ticket) {
                $ticket_num = $member_ticket['num'];
            }
        }
        msg(0, "查询成功", $ticket_num);
    }

    public function getHaiBaoUrl()
    {
        msg(0, config('site.haibao_img'), '');
    }

    //开发票接口
    public function ToInvoice()
    {
        $data = $this->request->param();//business_id 服务站id 购买水票填写0//type '1直接购买订单 2购买水票订单', //order_id 0待开 1已开
        $where[] = ['order_id', '=', $data['order_id']];
        $where[] = ['type', '=', $data['type']];
        //todo 创建订单是否属于本用户 确定订单完成后才能开
        if ($data['type'] == 1) {
            $InvoiceInfo = Db::name('order')->find($data['order_id']);
        } else {
            $InvoiceInfo = Db::name('member_watero')->find($data['order_id']);
        }
        if (!$InvoiceInfo) {
            msg(-1, '订单不存在', '');
        }
        $invoice_info = Db::name('invoice')->where($where)->find();
        if ($invoice_info) {
            msg(-1, '订单已申请开票', '');
        }
//        $invoice_msg=Db::name('invoice_msg')->where('member_id',$this->memberId)->find();
//        if(!$invoice_msg){
//            msg(-2, '请填写开票信息', '');
//        }
        $insert_data = array(
            'order_id' => $data['order_id'],
            'business_id' => $data['business_id'],
            'member_id' => $this->memberId,
            'type' => $data['type'],
            'create_time' => time(),
            'invoice_type' => $data['invoice_type'],
            'invoice_head' => $data['invoice_head'],
            'tax_no' => $data['tax_no'],
            'email' => $data['email'],
            'bank' => $data['bank'],
            'bank_address' => $data['bank_address'],
            'bank_phone' => $data['bank_phone'],
            'bank_no' => $data['bank_no'],
            'company_address' => $data['company_address'],
            'invoice_remark' => $data['invoice_remark'],
            'price' => $InvoiceInfo['price'],
            'order_no' => $InvoiceInfo['order_no'],
            'phone' => $data['phone']
        );
        Db::startTrans();
        try {
            $invoice_info = Db::name('invoice')->insertGetId($insert_data);
            Db::commit();
            msg(0, '新增成功', $invoice_info);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取水票购买订单
    public function waterTicketList()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['status', '=', 1];
        $data = Db::name('member_watero')
            ->order('pay_time desc')
            ->where($where)
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                return $item;
            });
        msg(0, '查询完成', $data);
    }

    //购物后给服务站发送微信消息
    public function sendXcxMessage()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];//订单id
        $thing15 = $data['thing15'];//联系人
        $phone_number16 = $data['phone_number16'];//联系电话
        $thing7 = $data['thing7'];//备注
        $order_info = Db::name('order')->find($order_id);
        $business_info = Db::name('business')->find($order_info['business_id']);
        $bindMember = Db::name('member')->find($business_info['member_id']);
        if (!$bindMember) {
            msg(-1, '绑定商家空', '');
        }
        $config = [
            'app_id' => config('wechat.appID'),
            'secret' => config('wechat.AppSecret'),
        ];
        $app = Factory::miniProgram($config);
//        $data = $app->subscribe_message->getTemplates();
        $send_data = [
            'template_id' => 'd4O22slspID-Z5Yb4lIBE0kWczvf094h30CD6jWgPZw', // 所需下发的订阅模板id
            'touser' => $bindMember['openid'],     // 接收者（用户）的 openid
            'page' => 'pages1/order/orderAd/orderAd?i=2',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'character_string1' => [
                    'value' => $order_info['order_no'],
                ],
//                'time4' => [
//                    'value' => date('Y-m-d H:i:s', $order_info['pay_time']),
//                ],
                'thing10' => [
                    'value' => $thing15,
                ],
                'phone_number11' => [
                    'value' => $phone_number16,
                ],
                'thing16' => [
                    'value' => $thing7,
                ],
            ],
        ];
        $data = $app->subscribe_message->send($send_data);
        msg(0, '发送完成', $data);
    }

    //退款发送微信通知
    public function sendXcxMessage2()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];//订单id
        $amount2 = $data['amount'];//订单金额
        $thing5 = $data['mname'];//操作人

        $order_info = Db::name('order')->find($order_id);
        $business_info = Db::name('business')->find($order_info['business_id']);
        $bindMember = Db::name('member')->find($business_info['member_id']);
        if (!$bindMember) {
            msg(-1, '绑定商家空', '');
        }
        $config = [
            'app_id' => config('wechat.appID'),
            'secret' => config('wechat.AppSecret'),
        ];
        $app = Factory::miniProgram($config);
        $send_data = [
            'template_id' => 'qAbgXowhLdGTYVkNSpbiv5oqCj350dYEmg1QrXkpaw8', // 所需下发的订阅模板id
            'touser' => $bindMember['openid'],     // 接收者（用户）的 openid
            'page' => 'pages1/order/orderAd/orderAd?i=2',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'character_string1' => [
                    'value' => $order_info['order_no'],
                ],
                'amount2' => [
                    'value' => $amount2,
                ],
                'thing5' => [
                    'value' => $thing5,
                ],
            ],
        ];
        $data = $app->subscribe_message->send($send_data);
        msg(0, '发送完成', $data);
    }



    /**
     * 提交成为商家申请意向
     */
    public function toIntention()
    {
        $param = $this->request->post('');
        $result = $this->validate($param, 'intention.insert');
        if (true !== $result) {
            msg(-1, $result, '');
        }
        $insert_data = array(
            'name' => $param['name'],
            'phone' => $param['phone'],
            'province' => $param['province'],
            'city' => $param['city'],
            'area' => $param['area'],
            'address' => $param['address'],
            'create_time' => time(),
            'member_id' => $this->memberId
        );
        Db::startTrans();
        try {
            $intention_info = Db::name('intention')->insertGetId($insert_data);
            Db::commit();
            msg(0, '新增成功', $intention_info);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    public function refund(){
        $data = $this->request->param();
        $order_id = $data['order_id'];//订单id
        //order_no
        $order_info=Db::name('order')
            ->where('id',$order_id)
            ->find();
        if (!$order_info){
            msg(-1, '订单不存在', '');
        }
        if($order_info['status']!=1){
            msg(-1, '当前订单状态不可退款', '');
        }
        $update_data=array(
            'id'=>$order_id,
            'status'=>6,
            'is_tui'=>1,
            'pay_status'=>0,
            'tui_time'=>time(),
            'write_code_digits'=>null,
            'write_code'=>null
        );
        Db::startTrans();
        try {
            //todo  pay_type 支付方式 1水卡支付 2直接支付
            if($order_info['pay_type']==1&& $order_info['status']==1){
                $order_detail=Db::name('order_detail')
                    ->where('order_id',$order_id)
                    ->find();
                $order_detail['goods_id'];
                $order_detail['goods_num'];
                //水票历史
                $water_history=array(
                    'member_id'=>$this->memberId,
                    'goods_id'=>$order_detail['goods_id'],
                    'num'=>$order_detail['goods_num'],
                    'type'=>1,
                    'create_time'=>time()
                );
                Db::name('member_ticket_history')->insertGetId($water_history);
                //水票数量
                Db::name('member_ticket')
                    ->where(['member_id'=>$this->memberId,'goods_id'=> $order_detail['goods_id']])
                    ->setInc('num',$order_detail['goods_num']);
                //todo  水票返回
            }else{
                //todo 支付钱数返回
                $config = config('wechat.wxpay');
                $app = Factory::payment($config);
                $result = $app->refund->byOutTradeNumber($order_info['order_no'], $order_info['order_no'], $order_info['price']*100, $order_info['price']*100, [
                    // 可在此处传入其他参数，详细参数见微信支付文档
                    'refund_desc' => '订单退款',
                ]);
//                msg(0, '修改成功', $result);
            }
            $order_info = Db::name('order')->update($update_data);
            Db::commit();
            msg(0, '修改成功', $order_info);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }



}